//
//  FindViewController.m
//  Funny
//
//  Created by dllo on 15/10/27.
//  Copyright © 2015年 King. All rights reserved.
//

#import "FindViewController.h"

@interface FindViewController ()<UITableViewDataSource, UITableViewDelegate, CityListViewControllerDelegate, CLLocationManagerDelegate>
#import "SearchViewController.h"

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIButton *fieldButton;
@property (nonatomic, strong) UILabel *lable;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, assign) NSInteger flag;

@end

@implementation FindViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.flag = 1;
    [self createTableView];
    [self location];
    self.title = @"周边";
    [self.view addSubview:self.lable];
    
    self.tableView.header = [MyRefreshHeaderGif headerWithRefreshingTarget:self refreshingAction:@selector(handleDataPullDown)];
    self.tableView.footer = [MyRefreshFooterGif footerWithRefreshingTarget:self refreshingAction:@selector(handleDataPullUp)];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"定位中"
                                   style:UIBarButtonItemStylePlain
                                   target:self
                                   action:@selector(leftButtonAction:)];
    self.navigationItem.leftBarButtonItem = leftButton;
}

- (UILabel *)lable
{
    if (!_lable) {
        self.lable = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth / 2 - 100, 100, 200, 30)];
        _lable.textAlignment = NSTextAlignmentCenter;
        _lable.text = @"加载中 , 请稍后...";
        _lable.textColor = [UIColor grayColor];
    }
    return _lable;
}

- (void)leftButtonAction:(UIButton *)btn
{
    CityListViewController *cityList = [[CityListViewController alloc]init];
    cityList.name = self.city;
    cityList.delegate = self;
    [self.navigationController pushViewController:cityList animated:YES];
}

// 定位
- (void)location
{
    self.locationManager = [[CLLocationManager alloc] init] ;
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [self.locationManager requestAlwaysAuthorization];
        
    }
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = [[CLLocation alloc]init];
    location = [locations lastObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placemark = placemarks[0];
            NSString *city = placemark.locality;
            if (!city) {
                city = placemark.administrativeArea;
            }
            self.city = city;
            UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]
                                           initWithTitle:[NSString stringWithFormat:@"%@",city]
                                           style:UIBarButtonItemStylePlain
                                           target:self
                                           action:@selector(leftButtonAction:)];
            self.navigationItem.leftBarButtonItem = leftButton;
            [self handleDataForCityCode];
        }
    }];
    [self.locationManager stopUpdatingLocation];
}

#pragma mark -dataArray懒加载
- (NSArray *)dataArray
{
    if (!_dataArray) {
        self.dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark -创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 44) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerClass:[FindTableViewCell class] forCellReuseIdentifier:@"tableView"];
    [self.view addSubview:_tableView];
}

#pragma mark -tableView方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ScreenWidth / 3 * 2 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FindTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableView"];
    cell.model = [self.dataArray objectAtIndex:indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DetailViewController *detail = [[DetailViewController alloc]init];
    detail.productId = [[self.dataArray objectAtIndex:indexPath.row] productId];
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)passValue:(NSString *)text
{
    self.cityCode = text;
    self.dataArray = NULL;
    [self handleData];
}

// 下拉刷新

- (void)handleDataPullDown
{
    self.flag = 1;
    NSString *str = [NSString stringWithFormat:@"http://apiphp.yaochufa.com/playpoint/quality?userId=0&pageIndex=%ld&version=4.4.0&imei=00000000-58ca-002b-e3ba-8a9569d38c36&currentCityCode=210200&system=android&deviceToken=00000000-58ca-002b-e3ba-8a9569d38c36&regId=000e88f6400&cityCode=%@&tabType=1&channel=nearme&latitude=38.883733&longitude=121.54421",(long)self.flag,self.cityCode];
    [HandleData handleDataWithUrl:str completion:^(id data) {
        self.dataArray = [NSMutableArray array];
        NSDictionary *dic = data;
        NSArray *arr = [dic objectForKey:@"content"];
        if (arr.count == 0) {
            self.dataArray = arr.mutableCopy;
            _lable.alpha = 1;
            _lable.text = @"还未推出!敬请期待";
        }
        else{
            for (NSDictionary *dataDic in arr) {
                FindModel *model = [FindModel modelWithDic:dataDic];
                [self.dataArray addObject:model];
            }
            _lable.alpha = 0;
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    }];
}

// 上拉加载

- (void)handleDataPullUp
{
    self.flag += 1;
    [self handleData];
    [self.tableView.footer endRefreshing];
}

- (void)handleDataForCityCode
{
    NSString *str = @"http://appapi.yaochufa.com/v2/Position/GetCityList?machineCode=00000000-58ca-002b-e3ba-8a9569d38c36&version=4.4.0&system=android&channel=nearme";
    [HandleData handleDataWithUrl:str completion:^(id data) {
        for (NSDictionary *dic in [[data objectForKey:@"data"] objectForKey:@"positionCity"]) {
            NSString *key = [dic objectForKey:@"cityName"];
            if ([key isEqualToString:self.city]) {
                self.cityCode = [dic objectForKey:@"cityCode"];
                break;
            }
        }
        [self handleData];
    }];
}

#pragma mark -处理数据
- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://apiphp.yaochufa.com/playpoint/quality?userId=0&pageIndex=%ld&version=4.4.0&imei=00000000-58ca-002b-e3ba-8a9569d38c36&currentCityCode=210200&system=android&deviceToken=00000000-58ca-002b-e3ba-8a9569d38c36&regId=000e88f6400&cityCode=%@&tabType=1&channel=nearme&latitude=38.883733&longitude=121.54421",(long)self.flag,self.cityCode];
    [HandleData handleDataWithUrl:str completion:^(id data) {
        NSDictionary *dic = data;
        NSArray *arr = [dic objectForKey:@"content"];
        if (arr.count == 0) {
            self.dataArray = arr.mutableCopy;
            _lable.alpha = 1;
            _lable.text = @"还未推出!敬请期待";
        }
        else{
            for (NSDictionary *dataDic in arr) {
                FindModel *model = [FindModel modelWithDic:dataDic];
                [self.dataArray addObject:model];
            }
            _lable.alpha = 0;
        }
        [self.tableView reloadData];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
